/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-24 23:34:52
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.api.base.dto.ApiJobDto;
import com.joysuch.wwyt.api.basedata.service.BpJobSyncService;
import com.joysuch.wwyt.bp.bean.BpJobSearchBean;
import com.joysuch.wwyt.bp.entity.BpJob;
import com.joysuch.wwyt.bp.entity.dsl.QBpJob;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.bp.service.BpJobService;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dzhapi.bean.ApiBaseUserBean;
import com.joysuch.wwyt.dzhapi.bean.ApiBpJobBean;
import com.joysuch.wwyt.dzhapi.dto.BuildDataDto;
import com.joysuch.wwyt.dzhapi.mapper.ApiBaseUserMapper;
import com.joysuch.wwyt.dzhapi.mapper.ApiBpJobMapper;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
@Slf4j
public class BpJobServiceImpl implements BpJobService {

    @Autowired
    private BpJobDao dao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;

    @Autowired
    private BpJobSyncService jobSyncService;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private ApiBpJobMapper jobMapper;
    @Autowired
    private ApiBaseUserMapper userMapper;

    @Override
    public void add(BpJob entity) throws Exception {
        if (entity.getStaffCount() == null) {
            entity.setStaffCount(0);
        }
        //名称判重
        int count = dao.countByName(entity.getName());
        if (count > 0) {
            throw new IllegalArgumentException("此名称已存在");
        }
        entity.setUniqueId(String.valueOf(SnowFlakeUtil.getJobId()));
        if (entity.getRiskDistrictId() != null) {
            Optional<RiskDistrict> ord = riskDistrictDao.findById(entity.getRiskDistrictId());
            if (ord.isPresent()) {
                entity.setRiskDistrictName(ord.get().getName());
            }
        }
        //调用同步接口
        entity.setOrgCode(Context.getCompanyCode());
        entity.setTenentId(Context.getCurrentTenantId());
        boolean sync = jobSyncService.syncjob(entity);
        if (sync) {
            entity.setLocateSync(true);
        } else {
            entity.setLocateSync(false);
        }

        dao.save(entity);
    }

    @Override
    public void update(BpJob entity) throws Exception {
        BpJob content = dao.findById(entity.getId()).get();
        if (!entity.getName().equals(content.getName())) {
            //名称判重
            int count = dao.countByName(entity.getName());
            if (count > 0) {
                throw new IllegalArgumentException("此名称已存在");
            }
        }
        content.setName(entity.getName());
        content.setDescription(entity.getDescription());
        //岗位最小人数
        content.setMinPeopleNumber(entity.getMinPeopleNumber());
        //岗位最大人数
        content.setMaxPeopleNumber(entity.getMaxPeopleNumber());
        //风险分区id
        content.setRiskDistrictId(entity.getRiskDistrictId());
        //岗位地点
        content.setSite(entity.getSite());
        if (content.getUniqueId() == null) {
            content.setUniqueId(String.valueOf(SnowFlakeUtil.getJobId()));
        }
        if (entity.getRiskDistrictId() != null) {
            Optional<RiskDistrict> ord = riskDistrictDao.findById(entity.getRiskDistrictId());
            if (ord.isPresent()) {
                content.setRiskDistrictName(ord.get().getName());
            }
        }
        //调用同步接口
        boolean sync = jobSyncService.syncjob(content);
        if (sync) {
            content.setLocateSync(true);
        } else {
            content.setLocateSync(false);
        }
        content.setUpdateTime(new Date());
        content.setUpdateBy(Context.getCurrentUserId());
        dao.save(content);
    }

    @Override
    public Page<BpJob> findByPage(Pageable page, BpJobSearchBean bpJobSearchBean) {
        QBpJob q = QBpJob.bpJob;
        Predicate p = bpJobSearchBean.getName() != null ? q.name.contains(bpJobSearchBean.getName()) : null;
        p = ExpressionUtils.and(p,
                ExpressionUtils.or(q.showState.notIn(DataStateTypes.DELETE.getState()),
                        q.showState.isNull()));
        if (bpJobSearchBean.getLocateSync() != null){
            p = ExpressionUtils.and(p,q.locateSync.eq(bpJobSearchBean.getLocateSync()));
        }
        p = StringUtils.isNotBlank(bpJobSearchBean.getNameOrCode()) ? ExpressionUtils.and(p, ExpressionUtils.or(q.name.contains(bpJobSearchBean.getNameOrCode()), q.id.like("%" + bpJobSearchBean.getNameOrCode() + "%"))) : p;
        Page<BpJob> all = p == null ? dao.findAll(page) : dao.findAll(p, page);
        for (BpJob bpJob : all) {
            bpJob.setStaffCount(baseUserDao.countByJob(bpJob.getId()));
            if (bpJob.getRiskDistrictId() != null) {
                Optional<RiskDistrict> ord = riskDistrictDao.findById(bpJob.getRiskDistrictId());
                if (ord.isPresent() && (ord.get().getState() == null || ord.get().getState() != 44)) {
                    bpJob.setRiskDistrictName(ord.get().getName());
                }
            }
        }
        return all;
    }

    /**
     * 单个删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        BpJob job = dao.findById(id).get();
        List<BaseUser> users = baseUserDao.findByJob(id);
        if (!CollectionUtils.isEmpty(users)) {
            throw new IllegalArgumentException("该岗位(" + job.getName() + ")存在人员，请先移除人员后再删除岗位");
        }
        //调用同步接口
        boolean sync = jobSyncService.deleteSync(job.getUniqueId());
        if (sync) {
            job.setLocateSync(true);
        } else {
            job.setLocateSync(false);
        }
        job.setShowState(DataStateTypes.DELETE.getState());
        dao.save(job);
        // dao.deleteById(id);
    }

    @Override
    public void apiDelete(Long id, BuildDataDto dto) {
//        BpJob job = dao.findById(id).get();
        ApiBpJobBean jobBean = jobMapper.selectById(id);
        List<ApiBaseUserBean> users = userMapper.findByJob(id, dto.getTenentId(), dto.getOrgCode());
//        List<BaseUser> users = baseUserDao.findByJob(id);
        if (!CollectionUtils.isEmpty(users)) {
            throw new IllegalArgumentException("该岗位(" + jobBean.getName() + ")存在人员，请先移除人员后再删除岗位");
        }
        //调用同步接口
        boolean sync = jobSyncService.deleteSync(jobBean.getUniqueId());
        if (sync) {
            jobBean.setLocateSync(true);
        } else {
            jobBean.setLocateSync(false);
        }
        jobBean.setShowState(DataStateTypes.DELETE.getState());
        jobMapper.updateById(jobBean);
//        dao.save(job);
        // dao.deleteById(id);
    }

    /**
     * 单个删除跨建筑
     *
     * @param id
     */
    @Override
    public void deleteCross(Long id, String buildId) {
//        Context.setTenentIdOrgCodeIntercept(false);
        BpJob job = dao.findById(id).get();
        List<BaseUser> users = baseUserDao.findByJob(id);
//        Context.setTenentIdOrgCodeIntercept(true);
        if (!CollectionUtils.isEmpty(users)) {
            throw new IllegalArgumentException("该岗位(" + job.getName() + ")存在人员，请先移除人员后再删除岗位");
        }
        //调用同步接口
        boolean sync = jobSyncService.deleteSyncCross(job.getUniqueId(), job.getTenentId(), job.getOrgCode(), buildId);
        if (sync) {
            job.setLocateSync(true);
        } else {
            job.setLocateSync(false);
        }
        job.setShowState(DataStateTypes.DELETE.getState());
        dao.save(job);
        // dao.deleteById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public List<String> deleteByIds(List<Long> ids) {
        List<String> message = new ArrayList<>();
        if (CollectionUtils.isEmpty(ids)) {
            throw new IllegalArgumentException("请选择要删除的岗位");
        }
        for (Long id : ids) {
            try {
                delete(id);
            } catch (IllegalArgumentException e) {
                log.error(e.getMessage(), e);
                message.add(e.getMessage());
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
        return message;
    }

    @Override
    public BpJob findById(Long id) {

        return dao.findById(id).get();
    }

    @Override
    public List<BpJob> findAllJobByTenentId(Long tenentId) {
        return dao.findAllJobByTenentId(tenentId);
    }

    /**
     * 设置报警模板
     *
     * @param jobId
     * @param templateId
     * @return
     */
    @Override
    public BpJob editAlarmTemplate(Long jobId, Long templateId, String templateName) {
        BpJob job = dao.findById(jobId).orElseThrow(() -> new IllegalArgumentException("岗位不存在"));
        if (templateId != null && templateId.equals(0)) {
            templateId = null;
            templateName = null;
        }
        job.setAlarmTemplateId(templateId);
        job.setAlarmTemplateName(templateName);
        boolean sync = jobSyncService.updateSync(job);
        if (sync) {
            job.setLocateSync(true);
        } else {
            job.setLocateSync(false);
        }
        BpJob save = dao.save(job);
        return save;
    }

    @Override
    public List<SimpleSelectListBean> getList() {
        List<BpJob> all = dao.findAll();
        List<SimpleSelectListBean> list = new ArrayList<>();
        for (BpJob job : all) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setLabel(job.getName());
            bean.setValue(job.getId());
            list.add(bean);
        }
        return list;
    }

    @Override
    public List<ApiJobDto> getListForApi(String jobName, Long tenentId, String orgCode) {
        return jobMapper.getlistForApi(jobName,tenentId,orgCode);
    }

    @Override
    public com.baomidou.mybatisplus.extension.plugins.pagination.Page<ApiJobDto> getListByPageForApi(Integer page, Integer size, String jobName, Long tenentId, String orgCode) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<ApiJobDto> pageForApi = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<ApiJobDto>(page+1,size);
        return jobMapper.getlistByPageForApi(pageForApi,jobName, tenentId,orgCode);
    }

    @Override
    public List<ApiBpJobBean> findByIds(List<Long> jobIds) {
        List<ApiBpJobBean> list = jobMapper.selectBatchIds(jobIds);
        return list;
    }

}
